from starlette.middleware.cors import CORSMiddleware
from starlette.staticfiles import StaticFiles
from fastapi.responses import JSONResponse
from starlette.exceptions import HTTPException as StarletteHTTPException
from boot import Boot
from db.database import DB1, engine1
from loguru import logger
import logging
import apis
import customer
import users

from fastapi import FastAPI

app = FastAPI()

# 初始化数据库
DB1.metadata.create_all(bind=engine1)

# 初始化系统
Boot()

# 静态资源
app.mount("/static", StaticFiles(directory="./static"), name="static")

# 路由
app.include_router(users.router)
app.include_router(customer.router)
app.include_router(apis.router)

# 跨域设置
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


# 日志设置
@app.on_event("startup")
async def startup():
    logger = logging.getLogger("uvicorn.access")
    handler = logging.handlers.RotatingFileHandler(
        "./log/fastapi.log",
        encoding="utf-8",
        maxBytes=1024 * 1024,
        backupCount=10
    )
    handler.setFormatter(logging.Formatter("%(asctime)s - %(levelname)s - %(message)s"))
    logger.addHandler(handler)


# 错误响应
@app.exception_handler(StarletteHTTPException)
async def http_exception_handler(_, exc):
    """自定义错误响应"""
    return JSONResponse(exc.detail, status_code=exc.status_code)
